package com.heima.behavior.service.impl;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.model.behavior.dtos.NewBehaviorDTO;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    ApBehaviorEntryService behaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //1. 校验参数 文章id必须传
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            user = new ApUser();
        }
        //2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        ApBehaviorEntry behaviorEntry = behaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        //3. 判断阅读行为是否存在
        ApReadBehavior readBehavior = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(behaviorEntry.getId())
                .and("articleId").is(dto.getArticleId())), ApReadBehavior.class);
        //4. 存在  将阅读行为的count字段加1 并修改
        if (readBehavior != null) {
            readBehavior.setCount((short) (readBehavior.getCount() + 1));
            readBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(readBehavior);
        } else {
            //5. 不存在  创建阅读行为 并初始化count字段值为 1
            readBehavior = new ApReadBehavior();
            readBehavior.setEntryId(behaviorEntry.getId());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setCount((short) 1);
            readBehavior.setCreatedTime(new Date());
            mongoTemplate.insert(readBehavior);
        }
        //*****添加文章阅读-发送消息******
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, mess);
        log.info("阅读行为 发送消息 ==>{}",JSON.toJSONString(mess));
        return ResponseResult.okResult();
    }
}
